package com.scalar.chiptrack.operations.tapereel.actioncommands;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.release.ContactPerson;
import com.scalar.chiptrack.operations.release.ReleaseHelper;
import com.scalar.chiptrack.operations.release.dao.RelaseDAO;
import com.scalar.chiptrack.operations.release.forms.ReleaseInfoSetupForm;
import com.scalar.chiptrack.operations.tapereel.TapeReelRequest;
import com.scalar.chiptrack.operations.tapereel.dao.TapeReelRequestDAO;
import com.scalar.chiptrack.operations.tapereel.forms.TapeReelRequestForm;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;

/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: Apr 25, 2007
 * Time: 9:13:38 PM
 */
public class TapeReelRequestCloseCommand extends ActionCommand
{

    private static final String ACTION_NAME = "/tapeReelRequest.do";

    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws ScalarException
    {
        String isClosed                             = request.getParameter( "isClosed" );
        
        TapeReelRequestForm tapeReelRequestForm     = ( TapeReelRequestForm ) form;
        TapeReelRequest tapeReelRequest             = tapeReelRequestForm.getTapeReelRequest();
        ActionForward actionForward                 = mapping.findForward( "view" );
        HttpSession mSession                        = request.getSession();
        User user                                   = ( User ) mSession.getAttribute ( SessionKeys.USER_KEY );
        HashMap<String,String> errors               = new HashMap<String,String>();
        HashMap<String,String> info                 = new HashMap<String,String>();
        int tapeReelRequestId                       = -1;

        DBTransaction dbTransaction                 = null;
        boolean success                             = false;

        request.setAttribute( INFO_MESSAGES, info );
        request.setAttribute( ERROR_MESSAGES, errors );

        if ( user == null )
        {
            mSession.setAttribute ( SessionKeys.SOURCE_PAGE_KEY,  ACTION_NAME );
            return ( mapping.findForward ( "login" ) );
        }
        else
        {
            if ( user.isActionAllowed ( Functionality.TAPE_REEL_REQUEST , User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }
        try
        {
            if( "true".equalsIgnoreCase( isClosed ) )
            {
                actionForward = mapping.findForward( "search" );
                try
                {
                    dbTransaction = DBTransaction.getInstance();
                    dbTransaction.begin();

                    TapeReelRequestDAO.updateTapeReelRequestStatus( null, tapeReelRequest );

                    success = true;
                }
                catch( Exception e )
                {
                    e.printStackTrace();
                    throw new ScalarException( "Could not Close the Tape & Reel Request to database." );
                }
                finally
                {
                    if( dbTransaction != null ){
                        if( success == true ){
                            try{
                                dbTransaction.commit();
                                info.put ( "Tape & Reel Request has been Closed", null );
                            }catch( Exception e ){
                                e.printStackTrace();
                                errors.put ( "Error while committing the database ", null );
                            }
                        }
                        else
                        {
                            try{
                                dbTransaction.rollback();
                                errors.put ( "Tape & Reel Request Closing aborted", null );
                            }catch( Exception e ){
                                e.printStackTrace();
                                errors.put ( "Error occurred while rolling back", null );
                            }
                        }
                    }
                }


                try
                {
                    TapeReelRequest savedTapeReelRequest = TapeReelRequestDAO.getTapeReelRequest( null, tapeReelRequest.getTrRequestid() );
                    //TO SEND THE MAIL ALERTS TO VENDOR CONTACT PERSONS
                    TapeReelRequestDAO.sendTapeReelRequestMail( savedTapeReelRequest, user );
                }
                catch( Exception e )
                {
                    e.printStackTrace();
                    errors.put( "Could not send Tape & Reel Request Request Email", null );
                }

                tapeReelRequestForm.setTapeReelRequest( new TapeReelRequest() );
                request.setAttribute( "partNumbersList", TapeReelRequestDAO.loadTapeAndReelFgProducts() );
                request.setAttribute( "vendorsList", TapeReelRequestDAO.getTrLocations() );
                request.setAttribute( "statusList", TapeReelRequest.getStatusList() );
                 tapeReelRequestForm.getTapeReelRequest().setReqStatus("Issued_Pulled");
                info.put( "Tape & Reel Request has been Closed", null );
            }
            else
            {
                try
                {
                    tapeReelRequestId = Integer.parseInt( request.getParameter( "trReqId" ) );
                }
                catch( NumberFormatException nfe ) { tapeReelRequestId = -1; }

                tapeReelRequest.setTrRequestid( tapeReelRequestId );
                tapeReelRequest = TapeReelRequestDAO.loadTapeReelRerquestDetails( null, tapeReelRequest );
                tapeReelRequest.setReqStatus( TapeReelRequest.STAUS_CLOSED );
                tapeReelRequest.setLotList( TapeReelRequestDAO.getFGLotDetails( tapeReelRequest ) );

                tapeReelRequest.setPinCount( TapeReelRequestDAO.getProcessParameter( tapeReelRequest.getTrProcessStepId(), "PIN" ));
                tapeReelRequest.setPackageType( TapeReelRequestDAO.getProcessParameter( tapeReelRequest.getTrProcessStepId(), "PACKAGE ID" ));

                ReleaseInfoSetupForm releaseInfoSetupForm = null;
                releaseInfoSetupForm = new ReleaseInfoSetupForm();
                releaseInfoSetupForm.setVendorId(tapeReelRequest.getVendorId());
                releaseInfoSetupForm.setCategory("PROD");
                RelaseDAO.loadReleaseInfoSetup("Class Store", releaseInfoSetupForm);
                ArrayList<ContactPerson> vendorContactPersonsList = RelaseDAO.loadVendorContactPersonsList(null, releaseInfoSetupForm.getReleaseInfoSetupId());
                tapeReelRequest.setTrRequestAlerts(ReleaseHelper.getContactPersonsAsString("email", vendorContactPersonsList));
                ArrayList<ContactPerson> contactPersonsList = RelaseDAO.loadContactPersonsList(releaseInfoSetupForm.getReleaseInfoSetupId());
                tapeReelRequest.setInternalContactPersonEmail(ReleaseHelper.getContactPersonsAsString("email", contactPersonsList));

                tapeReelRequest.setVendorContactPersonsList(vendorContactPersonsList);
                tapeReelRequest.setContactPersonsList(contactPersonsList);
                tapeReelRequestForm.setTapeReelRequest( tapeReelRequest );

                request.setAttribute( "isClose", "true" );
            }

      }
      catch (Exception e)
      {
          errors.put( "Could not save the Tape & Reel Request", null );
          request.setAttribute("partNumbersList", TapeReelRequestDAO.loadTapeAndReelFgProducts() );
          request.setAttribute("vendorsList", TapeReelRequestDAO.getTrLocations());
          request.setAttribute("statusList", TapeReelRequest.getStatusList());
          tapeReelRequestForm.getTapeReelRequest().setReqStatus("Issued_Pulled");
          actionForward = mapping.findForward( "search" );
      }
      return actionForward;
    }
}
